package pzc.context.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NamingException;

public class ContextBinder {
	// private static Logger logger = Logger.getLogger(ContextBinder.class.getName());

	static {
		System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
		System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
	}

	public static void bind(String jndiName, Object obj) throws NamingException {

		File dir = new File(jndiName);

		List<String> pathList = new ArrayList<String>();

		while (dir != null) {
			pathList.add(0, dir.getName());
			dir = dir.getParentFile();
		}

		Context root = new InitialContext();
		Context tempContext = root;
		for (int i = 0; i < pathList.size(); i++) {
			String path = pathList.get(i);
			if (i < (pathList.size() - 1)) {
				try {
					tempContext = tempContext.createSubcontext(path);
				} catch (NameAlreadyBoundException ex) {
					// logger.info(path + " is already bound");
					Object o = tempContext.lookup(path);
					if (o instanceof Context) {
						tempContext = (Context) o;
					} else {
						throw ex;
					}
				}
			} else {
				tempContext.bind(path, obj);
			}
		}

		// ContextViewer.showAll(root);
	}
}
